<template>
  <view class="content" :style="{ paddingTop: statusBarHeight + 'px' }">
    <uni-nav-bar title="标品搜索" fixed :border="false" height="88rpx" background-color="#f7f7f7" left-icon="left"
      @clickLeft="onClickLeft"></uni-nav-bar>
    <view class="topCard">
      <uni-search-bar v-model="name" radius="100" placeholder="请输入" cancelButton="none"
        style="flex: 1;margin: 0;padding: 0;margin-right: 20rpx;" @confirm="searchFn" @clear="clearFn" />
      <view class="searchBtn" @click="searchFn">搜索</view>
    </view>
    <scroll-view :style="{ height: `calc(100vh - 168rpx - ${statusBarHeight}px)` }" style="overflow: hidden;" scroll-y
      enhanced :show-scrollbar="false" @scrolltolower="lower" :scroll-with-animation="true" refresher-enabled
      @refresherrefresh="refresherrefreshFn" :refresher-triggered="triggered" @touchmove.stop>
      <view class="list" v-if="goodsList.length > 0">
        <view class="item" v-for="(item, index) in goodsList" :key="item.id">
          <view class="pic">
            <image :src="item.storeImgUrl ? item.storeImgUrl : '/static/index/noneImg.png'" mode="aspectFill"></image>
            <view class="none" v-if="item.productState != '0'">
              <text v-if="item.productState == '1'">已停用</text>
              <text v-if="item.productState == '2'">已淘汰</text>
            </view>
          </view>
          <view class="info">
            <view class="title u-ellipsis">
              {{ item.commodityName }}
            </view>
            <view class="subtitle">
              <text>进价:{{ item.outboundPrice }}元</text>
              <text>零售价:{{ item.storePrice }}元</text>
              <text>毛利:{{ item.storePrice | subtract(item.outboundPrice) }}元</text>
              <text>库存:{{ item.stockNum }}</text>
              <text>销量:{{ item.salesNum }}</text>
              <text>期初库存:{{ item.initialInventory }}</text>
            </view>
            <view class="btn-list">
              <view class="btn type-1" @click="addProcure(item)" v-if="item.productState == '0' && item.isPick == '1' ">点采</view>
              <view class="btn type-1" @click.stop="updatePrice(item)">修改售价</view>
              <view class="btn type-1" @click.stop="() => { $navTo('./goodsDetail', { id: item.id }); newPage = '0'; }">详情
              </view>
            </view>
          </view>
        </view>
      </view>
      <uni-load-more :status="loading" v-if="goodsList.length > 0"></uni-load-more>
      <view
        style="width: 100%;height: 100%;background-color: #f7f7f7;display: flex;justify-content: center;align-items: center;"
        v-if="goodsList.length == 0">
        <image src="../../static/index/nonedata.png" mode="aspectFill" style="width: 400rpx;height: 400rpx;"></image>
      </view>
    </scroll-view>
    <uni-popup ref="inputDialog" type="dialog">
      <uni-popup-dialog ref="inputClose" mode="input" title="修改售价" @confirm="submit" @close="close" before-close>
        <template>
          <uni-forms ref="form" :model="formData" :rules="rules" label-width="50" validate-trigger="blur">
            <uni-forms-item label="售价:" name="storePrice">
              <uni-easyinput type="number" v-model="formData.storePrice" placeholder="请输入售价" :clearable="false" trim="all"
                adjust-position />
            </uni-forms-item>
          </uni-forms>
        </template>
      </uni-popup-dialog>
    </uni-popup>
    <cls-DragBtn is-dock :bottom-px="250" @btnClick="dianCaiclick">
      <view class="floatBox btn type-1">点采</view>
    </cls-DragBtn>
  </view>
</template>

<script>
import { reqSearchCommodity } from '@/apis/member.js'
import { DecimalUtils } from '../../utils/math';
import { reqUpdatePrice, reqAddPurchase } from '@/apis/goods.js';
export default {
  name: "InventoryInfo",
  data() {
    return {
      goodsList: [], // 供应链标品
      page: {
        pageNum: 1,
        pageSize: 15
      },
      type: '',
      name: '',
      triggered: false, // 是否触发下拉刷新
      loading: 'loading', // 是否触发上拉加载
      // 表单数据
      formData: {
        storePrice: null,
        id: '',
      },
      rules: {
        // 对name字段进行必填验证
        storePrice: {
          rules: [{
            required: true,
            errorMessage: '请输入售价',
          },
          {
            format: 'number',
            errorMessage: '售价格式错误'
          },
          {
            validateFunction: function (rule, value, data, callback) {
              let reg = /^(?!(^0$|0\.0{1,2}$))[0-9]+(\.[0-9]{1,2})?$/
              if (!reg.test(value)) {
                callback('售价最多两位小数')
              }
            }
          }
          ],
        }
      },
    }
  },
  filters: {
    subtract(value, params) {
      return DecimalUtils.subtract(value, params);
    }
  },
  onLoad(params) {
    // this.type = params.type
    // console.log('111', this.type);
    // this.reqSearchCommodity()
  },
  onShow() {
  },
  methods: {
    refresherrefreshFn() {
      console.log('233333');
      this.page.pageNum = 1
      this.triggered = true
      this.goodsList = []
      this.loading = "loading";
      this.reqSearchCommodity()
    },
    // 供应链 
    async reqSearchCommodity() {
      const res = await reqSearchCommodity({ ...this.page, retrieval: this.name })
      if (res.code === 200) {
        this.goodsList = [...this.goodsList, ...res.data.list]
        if (this.page.pageNum == 1 && this.goodsList.length == 0) {
          uni.showToast({
            title: '没有找到相关商品',
            icon: 'none'
          })
        }
        this.nextPage = res.data.nextPage
        console.log('goodsList:', this.goodsList);
        this.triggered = false
        if (res.data.isLastPage) {
          this.loading = "noMore"
        }
      }
    },
    lower() {
      console.log('222');
      if (this.loading == "noMore") {
        return;
      }
      this.page.pageNum++;
      this.loading = "loading";
      this.reqSearchCommodity()

    },
    searchFn() {
      console.log('1111111');
      if (!this.name) return uni.showToast({
        title: '请输入商品名称',
        icon: 'none'
      })
      this.page.pageNum = 1
      this.goodsList = []
      this.loading = "loading";
      this.reqSearchCommodity()
    },
    clearFn() {
      this.page.pageNum = 1
      this.goodsList = []
      this.loading = "loading";
      // this.reqSearchCommodity()
    },
    dianCaiclick() {
      this.$navTo('/pages/procure/waitSubmit')
    },
    updatePrice(item) {
      const firstCode = item.firstCode;
      const specificationList = item.specificationList;
      console.log(specificationList.length);
      if (specificationList.length === 1) {
        this.formData = {
          id: specificationList[0].id,
          storePrice: specificationList[0].storePrice
        }
        this.$refs.inputDialog.open();
      } else {
        this.newPage = "1";
        this.$navTo('./changePrice', { commodityId: item.commodityId });
      }
    },
    submit() {
      this.$refs.form.validate().then(async (suc) => {
        let res = await reqUpdatePrice({ ...this.formData });
        if (res.code === 200) {
          this.$refs.inputDialog.close();
          uni.utils.toast('修改成功', 'success')
          this.page = {
            pageNum: 1,
            pageSize: 15
          };
          this.goodsList = [];
          this.loading = "loading";
          this.reqSearchCommodity()

        }
      }).catch((err) => {
        console.log('失败')
      })
    },

    close() {
      this.formData = {
        id: '',
        storePrice: null
      };
      this.$refs.inputDialog.close();
      console.log("关闭");
    },
    async addProcure(item) {
      let commodityId = item.commodityId;
      let res = await reqAddPurchase({ commodityId });
      if (res.code === 200) {
        uni.utils.toast('添加点采成功', 'success');
      }
    }
  }
}
</script>
<style>
page {
  background: #f7f7f7;

}
</style>
<style lang="scss" scoped >
.content {
  height: 100vh;
  background-color: #f7f7f7;


}

.topCard {
  font-size: 26rpx;
  height: 80rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20rpx;
  // background-color: #fff;
  border: 1px solid #eee;
}

view {
  box-sizing: border-box;
}

.goodsname {
  font-weight: 600;
}

.list {
  padding: 0 15rpx;

  // flex: 1;
  // overflow: hidden;
  .item {
    display: flex;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #ccc;

    .pic {
      width: 240rpx;
      height: 240rpx;
      background-color: #f7f7f7;
      position: relative;

      .none {
        top: 0;
        left: 0;
        position: absolute;
        width: 240rpx;
        height: 240rpx;
        background: rgba(0, 0, 0, 0.6);
        border-radius: 10rpx;
        line-height: 240rpx;
        color: #fff;
        text-align: center;
        font-weight: bold;
        font-size: 34rpx;
      }

      image {
        width: 100%;
        height: 100%;
      }
    }

    .info {
      padding-left: 20rpx;
      flex: 1;
      min-width: 440rpx;
      display: flex;
      flex-direction: column;

      .title {
        width: 100%;
        margin-bottom: 5rpx;
        font-size: $uni-font-size-upBase;
        color: #000;
      }

      .subtitle {
        display: flex;
        flex-wrap: wrap;

        text {
          font-size: $uni-font-size-mini;
          width: 50%;
          color: #333;
          margin-bottom: 5rpx;
        }
      }

      .btn-list {
        margin-top: auto;
        display: flex;
        justify-content: flex-end;

        .btn {
          width: 120rpx;
          font-size: $uni-font-size-small;
          text-align: center;
          margin-right: 30rpx;
          border-radius: 5rpx;
          height: 60rpx;
          box-sizing: border-box;
          line-height: 60rpx;
        }
      }
    }
  }
}

.floatBox {
  width: 100rpx;
  height: 100rpx;
  line-height: 100rpx !important;
  box-shadow: 0 1px 5px 2px rgba(0, 0, 0, .3);
  font-weight: 600;
  text-align: center;
  border-radius: 50%;
  padding: 10rpx;
  box-sizing: border-box;
}
</style>
